package com.xiaoKe.zhonghzu.ui.fzxz;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.telephony.mbms.DownloadProgressListener;
import android.util.Log;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Toast;

import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.GridLayoutManager;

import com.bin.david.form.core.TableConfig;
import com.bin.david.form.data.CellInfo;
import com.bin.david.form.data.column.Column;
import com.bin.david.form.data.format.bg.BaseCellBackgroundFormat;
import com.bin.david.form.data.format.bg.ICellBackgroundFormat;
import com.bin.david.form.data.table.TableData;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.xiaoKe.zhonghzu.R;
import com.xiaoKe.zhonghzu.databinding.FragmentGather1Binding;
import com.xiaoKe.zhonghzu.global.base.VeinRouter;
import com.xiaoKe.zhonghzu.global.bean.ClFzData;
import com.xiaoKe.zhonghzu.global.bean.FzDataListBean;
import com.xiaoKe.zhonghzu.global.bean.GeneralData;
import com.xiaoKe.zhonghzu.global.dialog.ToastDialog;
import com.xiaoKe.zhonghzu.global.okhttp.ApiCallback;
import com.xiaoKe.zhonghzu.global.okhttp.ApiCallbackOnResponse;
import com.xiaoKe.zhonghzu.global.okhttp.ApiService;
import com.xiaoKe.zhonghzu.global.okhttp.DownloadManager;
import com.xiaoKe.zhonghzu.global.okhttp.RetrofitClient;
import com.xiaoKe.zhonghzu.global.tool.AppConstant;
import com.xiaoKe.zhonghzu.global.tool.LoggerTool;
import com.xiaoKe.zhonghzu.global.tool.SPUtils;
import com.xiaoKe.zhonghzu.global.tool.ToastUtils;
import com.xiaoKe.zhonghzu.ui.gather.CodeFragment;
import com.xiaoKe.zhonghzu.ui.onClick.NoDoubleClickListener;
import com.xiaoKe.zhonghzu.ui.onClick.OnClickListenerPositionInt;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Headers;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.http.GET;
import retrofit2.http.Streaming;

/**
 * @ProjectName : xiaoke-pad-zhongzhu
 * @Author : Shijingna
 * @Time : 2024/11/25 12:56
 * @Description : 采集
 */
public class Gather1Fragment extends CodeFragment<FragmentGather1Binding> {
    GatherAdapter gatherAdapter;
    List<GeneralData> list = new ArrayList<>();
    List<GeneralData> list7 = new ArrayList<>();
    String starTime;
    String endTime;

    @Override
    protected void initView() {

        list.add(new GeneralData("手动记录", R.mipmap.ic_add));
        list.add(new GeneralData("扫码记录", R.mipmap.ic_saoyisao));
        list.add(new GeneralData("拍照识别", R.mipmap.ic_pz));
        list.add(new GeneralData("待提交单据", R.mipmap.ic_dtj));
        binding.swipeRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 4));
        gatherAdapter = new GatherAdapter(list);
        binding.swipeRecyclerView.setAdapter(gatherAdapter);

        list7.add(new GeneralData("近1天", LocalDate.now().minusDays(1), 1));
        list7.add(new GeneralData("近15天", LocalDate.now().minusDays(15), 15));
        list7.add(new GeneralData("近30日", LocalDate.now().minusDays(30), 30));
        list7.add(new GeneralData("全部", null, 0));
        starTime = LocalDate.now().minusDays(1).toString();
        endTime = LocalDate.now().toString();
        binding.recyclerView7.into(list7, new OnClickListenerPositionInt() {
            @Override
            public void onItemClick(int item) {
                starTime = null == list7.get(item).getV() ? null : list7.get(item).getV().toString();
                endTime = LocalDate.now().toString();
                getData();
            }
        });
    }

    @Override
    protected void initData() {
        NoDoubleClickListener noDoubleClickListener = new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View view) {
                switch (view.getId()) {
                    case R.id.download:
                        XXPermissions();

                        break;
                }
            }
        };
        binding.download.setOnClickListener(noDoubleClickListener);
        gatherAdapter.setOnClickListenerPositionInt(new OnClickListenerPositionInt() {
            @Override
            public void onItemClick(int item) {
                Bundle bundle = new Bundle();
                switch (item) {
                    case 0://手动记录
                        bundle.putSerializable("data", null);
                        toFragmentPage(VeinRouter.REPRODUCTIVEADDFRAGMENT.setBundle(bundle));
                        break;
                    case 1://扫码记录
                        sweep();
                        break;
                    case 2:
                        ToastUtils.showLong("暂未开放，此功能");
                        break;
                    case 3:
                        toFragmentPage(VeinRouter.DTJFRAGMENT.setBundle(bundle));
                        break;

                }
            }
        });

    }

    public void XXPermissions() {
        XXPermissions.with(this)
                // 申请单个权限
                .permission(Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            toastDialog = new ToastDialog();
                            toastDialog.show(getChildFragmentManager(), "");
                            startDownload();
                        } else {
                            ToastUtils.showLong("获取部分权限成功，但部分权限未正常授予");
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            ToastUtils.showLong("被永久拒绝授权，请手动授予读写权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(getContext(), permissions);
                        } else {
                            ToastUtils.showLong("获取读写权限失败");
                        }
                    }
                });
    }

    @Override
    public void onResume() {
        super.onResume();
        gatherAdapter.notifyDataSetChanged();
        getData();
    }


    // 2. 执行下载并监听进度
    public void startDownload() {
        // 初始化下载管理器
        DownloadManager downloadManager = new DownloadManager();

// 设置监听器
        downloadManager.setListener(new DownloadManager.DownloadListener() {
            @Override
            public void onStart(long totalSize) {
                LoggerTool.d( "开始下载，总大小: " + totalSize + " 字节");
            }

            @Override
            public void onProgress(long currentBytes, long totalSize) {
                if (currentBytes!=0 && totalSize!=0){
                    int progress = (int) ((currentBytes * 100) / totalSize);
                    LoggerTool.d("下载进度: " + progress + "%");
                }

                // 更新UI进度条
            }

            @Override
            public void onSuccess(File file) {
                LoggerTool.d( "下载完成: " + file.getAbsolutePath());
                if (null!=toastDialog){
                    toastDialog.dismiss();
                }
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Uri path;
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                path = FileProvider.getUriForFile(getContext(), "com.xiaoKe.zhongzhu.FileProvider", file);
                            } else {
                                path = Uri.fromFile(file);
                            }
                            //注意intent用addFlags 如果intent在这行代码下使用setFlags会导致其他应用没有权限打开你的文件
                            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                            String type = getMimeType(file);
                            intent.setDataAndType(path, type);
                            //如果想让用户每次打开文件都自己选择（方便切换应用打开）加上下面这句代码
                            intent = Intent.createChooser(intent, "请选择打开此文件的应用");
                            startActivity(intent);


                        } catch (ActivityNotFoundException e) {

                        }
                    }
                }, 1000);

            }

            @Override
            public void onFailed(String errorMessage) {
                LoggerTool.e( "下载失败: " + errorMessage);
                if (null!=toastDialog){
                    toastDialog.dismiss();
                }
                // 显示错误信息
            }

            @Override
            public void onCanceled() {
                if (null!=toastDialog){
                    toastDialog.dismiss();
                }
                LoggerTool.d( "下载已取消");
            }
        });

// 开始下载
        downloadManager.startDownload(
                AppConstant.URL+"pmFzRecord/export", // 下载URL
                AppConstant.CACHE_FILE_PATH+LocalDate.now() + ".xlsx"     // 保存路径
        );


    }


    //获取文件的MIME注意不要用后缀名
    public static String getMimeType(File file) {
        String extension = getFileExtension(file.getName());
        if (extension != null) {
            MimeTypeMap mime = MimeTypeMap.getSingleton();
            return mime.getMimeTypeFromExtension(extension);
        }
        return null;
    }
    public static String getFileExtension(String fileName) {
        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex < 0) {
            return null;
        }
        return fileName.substring(dotIndex + 1);
    }
    public void getData() {
        String searchDateRange = null; //如果是全部的话就不需要传参数了
        if (null != starTime) {
            searchDateRange = starTime + "," + endTime;
        }
        RetrofitClient.getClient().create(ApiService.class).getFzDataList("繁殖性状-列表", searchDateRange)
                .enqueue(new ApiCallback(new ApiCallbackOnResponse() {
                    @Override
                    public void onResponse(Object v) {
                        FzDataListBean fzDataListBean = (FzDataListBean) v;
                        if (fzDataListBean.isSucceeded()) {
                            List<ClFzData> dataList = fzDataListBean.getData();
                            if (null != dataList && dataList.size() != 0) {
                                //奇偶行颜色
                                ICellBackgroundFormat<CellInfo> backgroundFormat = new BaseCellBackgroundFormat<CellInfo>() {
                                    @Override
                                    public int getBackGroundColor(CellInfo cellInfo) {
                                        if (cellInfo.row % 2 != 0) {
                                            return ContextCompat.getColor(getContext(), R.color.colorBgF8);
                                        }
                                        return TableConfig.INVALID_COLOR;
                                    }

                                    @Override
                                    public int getTextColor(CellInfo cellInfo) {
                                        if (cellInfo.column.getId() == 0) {
                                            return ContextCompat.getColor(getContext(), R.color.colorMain);
                                        }
                                        return TableConfig.INVALID_COLOR;
                                    }
                                };
                                binding.table.getConfig().setContentCellBackgroundFormat(backgroundFormat);
                                binding.table.setData(dataList);

                                // 获取“猪只编号”列（假设列 ID 为 0，需根据实际列顺序调整）
                                binding.table.getTableData().setOnItemClickListener(new TableData.OnItemClickListener() {
                                    @Override
                                    public void onClick(Column column, String value, Object o, int col, int row) {
                                        Bundle bundle = new Bundle();
                                        bundle.putLong("id", dataList.get(row).getId());
                                        toFragmentPage(VeinRouter.REPRODUCTIVEDETAILS.setBundle(bundle));
                                    }
                                });

                            } else {
                                getView().findViewById(R.id.line_zwsj).setVisibility(View.VISIBLE);
                            }


                        }
                    }
                }));


    }
}
